const { resolve } = require('path');
const { readdirSync } = require('fs');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WindiCSSWebpackPlugin = require('windicss-webpack-plugin');

const dev = process.env.NODE_ENV === 'development';

const entryDir = 'quiet2';

module.exports = ({ WEBPACK_BUNDLE }) => {
  const plugins = readdirSync('./template')
    .filter((filename) => /.html$/.test(filename))
    .map((filename) => new HtmlWebpackPlugin({
      filename: filename,
      template: resolve('template', filename)
    }))
  ;

  return {
    mode     : WEBPACK_BUNDLE ? 'production' : 'development',
    entry    : `./quiet2/index.js`,
    output   : {
      path      : resolve(`./dist/${entryDir}`),
      filename  : `${entryDir}.js`,
      publicPath: '/'
    },
    module   : {
      rules: [
        {
          test: /\.styl$/,
          use : [
            !WEBPACK_BUNDLE ? 'style-loader' : MiniCssExtractPlugin.loader,
            'css-loader',
            'postcss-loader',
            'stylus-loader'
          ]
        },
        {
          test: /\.css$/,
          use : [
            !WEBPACK_BUNDLE ? 'style-loader' : MiniCssExtractPlugin.loader,
            'css-loader',
            'postcss-loader'
          ]
        }
      ]
    },
    plugins  : [
      new WindiCSSWebpackPlugin(),
      new MiniCssExtractPlugin({
        filename: `${entryDir}.css`
      }),
      ...plugins,
    ].filter(Boolean),
    devServer: {
      static: resolve('public')
    }
  };
};
